package com.minhang.adsb.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.minhang.adsb.entity.ServerConfig;
import com.minhang.adsb.mapper.ServerConfigMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@EnableScheduling
public class ServerHealthCheckService {

    private final ServerConfigMapper serverConfigMapper;
    private final OkHttpClient healthCheckClient;

    public ServerHealthCheckService(ServerConfigMapper serverConfigMapper) {
        this.serverConfigMapper = serverConfigMapper;

        // 专用健康检查客户端（短超时配置）
        this.healthCheckClient = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false) // 禁用自动重试
                .build();
    }

    /**
     * 每5分钟执行一次健康检查
     */
//    @Scheduled(fixedRate = 1 * 60 * 1000)
    public void scheduledHealthCheck() {
        List<ServerConfig> allServers = serverConfigMapper.selectList(
                new LambdaQueryWrapper<ServerConfig>().select(ServerConfig::getId, ServerConfig::getEndpoint)
        );

        allServers.parallelStream().forEach(server -> {
            boolean isActive = checkServerStatus(server.getEndpoint());
            updateServerStatus(server.getId(), isActive);
        });
    }

    /**
     * 健康检查方法
     */
    private boolean checkServerStatus(String endpoint) {
        Request request = new Request.Builder()
                .url(endpoint + "/health") // 假设有健康检查端点
                .head() // 使用HEAD方法减少数据传输
                .build();

        try (Response response = healthCheckClient.newCall(request).execute()) {
            return response.isSuccessful();
        } catch (IOException e) {
            log.debug("服务器[{}]健康检查失败: {}", endpoint, e.getMessage());
            return false;
        }
    }

    /**
     * 更新服务器状态
     */
    private void updateServerStatus(Long serverId, boolean isActive) {
        int newStatus = isActive ? 1 : 0;

        // 只有当状态变化时才更新
        ServerConfig serverConfig = new ServerConfig();
        serverConfig.setIsActive(newStatus);
        serverConfig.setId(serverId);
        serverConfig.setLastCheckedTime(LocalDateTime.now());
        int result = serverConfigMapper.updateById(serverConfig);

        if (result > 0) {
            log.info("服务器[描述:{}]状态更新为: {}", serverId, newStatus);
        }
    }

    /**
     * 立即触发健康检查（用于手动测试）
     */
    public void triggerImmediateCheck() {
        scheduledHealthCheck();
    }
}